<template>
  <el-card shadow="never" class="border-0">
    <Search @search="getData" @reset="resetSearchForm" :model="searchForm">
      <search-item label="关键词" prop="title">
        <el-input v-model="searchForm.title" placeholder="商品名称" clearable />
      </search-item>
    </Search>

    <list-header @create="handleCreate" @refresh="getData" />

    <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">
      <el-table-column label="管理员" width="200">
        <template #default="{ row }">
          <div class="flex items-center">
            <!-- 如果获取不到row.avatar，就会使用内部的img -->
            <el-avatar :size="40" :src="row.avatar" @error="() => true">
              <img
                src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
              />
            </el-avatar>
            <div class="ml-3">
              <h6>{{ row.username }}</h6>
              <small>{{ row.id }}</small>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="所属管理员" align="center">
        <template #default="{ row }">
          {{ row.role?.name || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="120">
        <template #default="{ row }">
          <el-switch
            :disabled="row.super === 1"
            :model-value="row.status"
            :active-value="1"
            :inactive-value="0"
            :loading="row.statusLoading"
            @change="handleStatusChange($event, row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <small class="text-sm text-gray-500" v-if="scope.row.super === 1">
            暂无操作
          </small>

          <div v-else>
            <el-button
              type="primary"
              size="small"
              text
              @click="handleEdit(scope.row)"
            >
              修改
            </el-button>
            <el-popconfirm
              title="是否要删除该管理员？ "
              confirmButtonText="确认"
              cancelButtonText="取消"
              @confirm="handleDelete(scope.row.id)"
            >
              <template #reference>
                <el-button type="primary" size="small" text> 删除 </el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="flex items-center justify-center mt-5">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :current-page="currentPage"
        :page-size="limit"
        @current-change="getData"
      />
    </div>

    <FormDrawer
      ref="formDrawerRef"
      :title="drawerTitle"
      @submit="handleSumbit"
      @cancel="handleCancel"
    >
      <el-form
        :model="form"
        ref="formRef"
        :rules="rules"
        label-width="120px"
        :inline="false"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            placeholder="请输入密码"
            type="password"
            show-password
          />
        </el-form-item>

        <el-form-item label="头像" prop="avatar" ref="chooseImageUploadRef">
          <choose-image v-model="form.avatar" @upImgSuc="handleUpImgSuc" />
        </el-form-item>

        <el-form-item label="所属角色" prop="role_id">
          <el-select v-model="form.role_id" placeholder="请选择所属角色">
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
    </FormDrawer>
  </el-card>
</template>

<script setup>
  import { ref } from 'vue'
  import {
    getManagerListApi,
    updateManagerStatusApi,
    createManagerApi,
    updateManagerApi,
    deleteManagerApi,
  } from '@/api/manager.js'
  import FormDrawer from '@/components/FormDrawer.vue'
  import ChooseImage from '@/components/ChooseImage.vue'
  import ListHeader from '@/components/ListHeader.vue'
  import Search from '@/components/Search.vue'
  import SearchItem from '@/components/SearchItem.vue'
  import { useInitTable, useInitForm } from '@/hooks/useCommon.js'

  // 角色列表
  const roles = ref([])
  const {
    searchForm,
    resetSearchForm,
    tableData,
    loading,
    currentPage,
    total,
    limit,
    getData,
    handleDelete,
    handleStatusChange,
  } = useInitTable({
    // 搜索需要的参数
    searchForm: {
      keyword: '',
    },
    // 获取表单的api
    getlist: getManagerListApi,
    delete: deleteManagerApi,
    updateStatus: updateManagerStatusApi,
    // 获取表单成功的回调
    onGetListSuccess: (res) => {
      tableData.value = res.list.map((o) => {
        o.statusLoading = false
        return o
      })
      total.value = res.totalCount
      roles.value = res.roles
    },
  })

  const {
    formDrawerRef,
    formRef,
    form,
    rules,
    drawerTitle,
    handleCreate,
    handleEdit,
    handleSumbit,
    handleCancel,
  } = useInitForm({
    form: {
      username: '',
      password: '',
      role_id: null,
      status: 1,
      avatar: '',
    },
    rules: {
      username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
      password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      role_id: [
        { required: true, message: '请选择所属管理员', trigger: 'change' },
      ],
      avatar: [{ required: true, message: '请上传图片', trigger: 'change' }],
    },
    getData,
    create: createManagerApi,
    update: updateManagerApi,
  })

  // 上传图片成功
  const chooseImageUploadRef = ref(null)
  function handleUpImgSuc() {
    chooseImageUploadRef.value.clearValidate()
  }
</script>

<style scoped>
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
</style>
